import { getCsrf, getHref, getPageSourceInfo } from "../../../../shared/util";
import { searchCompany, submitForm } from "../../http/suppiler";
import { FieldType } from "./type";

interface AddressVo {
	divisionLevel: number;
	historyParentIdList: string[];
	pinyin: string;
	divisionLeaf: boolean;
	disable: boolean;
	countryCode: string;
	divisionName: string;
	divisionNameLanguage: string;
	divisionId: number;
	class: string;
	divisionAbbName: string;
	parentId: number;
}

interface JsonpResult<T> {
	total: number;
	dateline: number;
	success: boolean;
	values: T;
	class: string;
}

export const handleAddressVO = (result: JsonpResult<AddressVo[]>) => {
	return result.values.map((item) => {
		return {
			label: item.divisionName,
			value: item.divisionName + "_" + item.divisionId,
			isLeaf: item.divisionLeaf,
		};
	});
};

export const handleSearchCompanyRes = (result: JsonpResult<string[]>) => {
	if (result.total < 1) return [];
	return result.values.map((item) => {
		return {
			label: item,
			value: item,
		};
	});
};

let currentValue = "";
export const fetchCompanyData = (searchValue: string, callback: Function) => {
	currentValue = searchValue;
	const fetchData = () => {
		searchCompany({ companyName: searchValue }).then((res) => {
			if (currentValue == searchValue) {
				callback(handleSearchCompanyRes(res));
			}
		});
	};

	if (searchValue) {
		fetchData();
	} else {
		callback([]);
	}
};

export interface CompanyInfo {
	bizRegNo: string;
	ENT_NAME: string;
	address: string;
	creditCode: string;
	addressVo: {
		class: string;
		regionCode: string;
		cityName: string;
		provinceCode: string;
		cityCode: string;
		streetCode: string;
		regionName: string;
		provinceName: string;
		streetName: string;
	};
}

export const handleCompanyInfo = (result: JsonpResult<CompanyInfo>) => {
	if (!result.values) return {};
	const { provinceName, provinceCode, cityName, cityCode, regionName, regionCode, streetName, streetCode } =
		result.values.addressVo;

	const addressVo = [provinceName, cityName];
	regionName && addressVo.push(regionName);
	streetName && addressVo.push(streetName);

	return {
		addressVo,
		address: result.values.address,
	};
};

interface MoreInfoType {
	origin: null;
	configurationStr: string;
	pcBackground: null;
	wirelessBackground: null;
	agreement: null;
}

interface ApiResult<T> {
	success: boolean;
	errorMsg: null;
	errorCode: null;
	values: T;
}

export const handleMoreInfoConfig = (result: MoreInfoType) => {
	const escape2Html = (str: string) => {
		const arrEntities: any = { lt: "<", gt: ">", nbsp: " ", amp: "&", quot: '"' };
		return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
			return arrEntities[t];
		});
	};

	return (
		JSON.parse(escape2Html(result.configurationStr))[0].value?.map((item: any) => {
			item.className = "more-info-item";
			return item;
		}) || []
	);
};

export const clearNotNumber = (value: string) => {
	if (/^\d*&/.test(value)) {
		return value;
	}
	return value.replace(/[^\d]+/, "");
};

export const generateFormData = (values: FieldType, companyInfo: CompanyInfo, addressFrom: "user" | "api") => {
	//handle address vo
	let addressVoProject = {} as CompanyInfo["addressVo"];
	if (addressFrom == "user") {
		const addressVo = values.addressVo;
		const addressLevel = [
			["province", "provinceCode"],
			["city", "cityCode"],
			["district", "districtCode"],
			["street", "streetCode"],
		];
		addressVoProject = addressVo?.reduce((res, next, index) => {
			const [value0, value1] = next.split("_");
			res[addressLevel[index][0]] = value0;
			res[addressLevel[index][1]] = value1;
			return res;
		}, {} as any);
	} else {
		//
		const { provinceName, provinceCode, cityName, cityCode, regionName, regionCode, streetName, streetCode } =
			companyInfo?.addressVo as any;

		addressVoProject.provinceName = provinceName;
		addressVoProject.provinceCode = provinceCode;
		addressVoProject.cityName = cityName;
		addressVoProject.cityCode = cityCode;
		addressVoProject.regionName = regionName || "";
		addressVoProject.regionCode = regionCode || "";
		addressVoProject.streetName = streetName || "";
		addressVoProject.streetCode = streetCode || "";
	}

	// add detail address and company name
	const formData = {
		...addressVoProject,
		address: values.address,
		companyName: values.companyName,
	} as unknown as Parameters<typeof submitForm>[0]["data"];

	if (addressFrom === "api") {
		formData.socialCreditCode = companyInfo?.creditCode || "";
	}

	//user info
	formData.linkManName = values.username || "";
	formData.mobilePhone = values.phone || "";
	formData.countryPhoneCode = "86";

	//local
	formData.local = formData.streetCode;

	const { origin, joinSource } = getPageSourceInfo();

	formData.origin = origin;
	formData.willingnessKeys = values.moreInfo || [];
	formData.pageUrl = getHref();
	formData.joinSource = joinSource;

	return {
		phone: values.phone,
		messageCode: values.code,
		data: JSON.stringify(formData),
		pcsrf: getCsrf(),
	};
};
